from django.shortcuts import render

# Create your views here.
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework import status
from .models import McHospitalLevel
from .serializers import McHospitalLevelSerializer


@api_view(['GET'])
def hospital_level_list(request):
    items = McHospitalLevel.objects.all().order_by('-created_time')
    serializer = McHospitalLevelSerializer(items, many=True)
    return Response(serializer.data)


@api_view(['GET'])
def hospital_level_detail(request, pk):
    try:
        item = McHospitalLevel.objects.get(pk=pk)
    except McHospitalLevel.DoesNotExist:
        return Response({'error': 'Not found'}, status=status.HTTP_404_NOT_FOUND)
    serializer = McHospitalLevelSerializer(item)
    return Response(serializer.data)


@api_view(['POST'])
def hospital_level_create(request):
    serializer = McHospitalLevelSerializer(data=request.data)
    if serializer.is_valid():
        serializer.save()
        return Response(serializer.data, status=status.HTTP_201_CREATED)
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


@api_view(['PUT'])
def hospital_level_update(request, pk):
    try:
        item = McHospitalLevel.objects.get(pk=pk)
    except McHospitalLevel.DoesNotExist:
        return Response({'error': 'Not found'}, status=status.HTTP_404_NOT_FOUND)
    serializer = McHospitalLevelSerializer(item, data=request.data)
    if serializer.is_valid():
        serializer.save()
        return Response(serializer.data)
    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)


@api_view(['DELETE'])
def hospital_level_delete(request, pk):
    try:
        item = McHospitalLevel.objects.get(pk=pk)
    except McHospitalLevel.DoesNotExist:
        return Response({'error': 'Not found'}, status=status.HTTP_404_NOT_FOUND)
    item.delete()
    return Response(status=status.HTTP_204_NO_CONTENT)
